import React from 'react'
import SearchHeader from '../../components/SearchHeader'
import {getLocalCity} from '../../utils/localCity'
import {Flex, Toast} from 'antd-mobile'
import styles from './index.module.css'
import Filter from './components/Filter/index'
import { API } from '../../utils/api'
import {List, WindowScroller, AutoSizer, InfiniteLoader} from 'react-virtualized'
import HouseItem from '../../components/HouseItem'
import {BASEURL} from '../../utils/baseurl'
import Sticky from '../../components/Sticky'
import NoHouse from '../../components/NoHouse'

export default class HouseList extends React.Component {
  state = {
    localCity: '上海',
    localValue: '',
    list: [],
    count: 0,
    isShow: true
  }

  filters = {}

  async componentDidMount() {
    await this.getCityName()
    this.getHouseList()
  }

  async getCityName() {
    const {label, value} = await getLocalCity()
    this.setState({
      localCity: label,
      localValue: value
    })
  }

  onFilters = (filters) => {
    window.scrollTo(0, 0)
    this.filters = filters
    this.getHouseList()
  }

  getHouseList = async () => {
    this.setState({
      isShow: false
    })
    Toast.loading('加载中...', 0)
    const { data } = await API.get('/houses', {
      params: {
        cityId: this.state.localValue,
        ...this.filters,
        start: 1,
        end: 20
      }
    })
    this.setState({
      isShow: true
    })
    Toast.hide()
    if(data.body.count !== 0) {
      Toast.info(`加载了${data.body.count}条数据`, 2, null, false)
    }
    
    this.setState({
      list: data.body.list,
      count: data.body.count
    })
  }

  rowRenderer = ({
    key, // Unique key within array of rows
    index, // Index of row within collection
    isScrolling, // The List is currently being scrolled
    isVisible, // This row is visible within the List (eg it is not an overscanned row)
    style, // Style object to be applied to row (to position it)
  }) => {
    const {list} = this.state

    if(!list[index]) {
      return <div key={key} style={style}>
        <p className={styles.pBox}></p>
      </div>
    }

    const {houseImg: src, title, desc, tags, price, houseCode} = list[index]
    return (
      <div key={key} style={style} className={styles.housebox}>
        <HouseItem 
          onClick={()=>this.props.history.push(`/detail/${houseCode}`)}
          src={BASEURL + src}
          title={title}
          desc={desc}
          tags={tags}
          price={price}
        />
      </div>
    );
  }

  // 判断每一行数据是否加载完毕
  isRowLoaded = ({ index }) => {
    return !!this.state.list[index]
  }
  // 用来获取更多房屋列表数据
  // 注意，该方法的返回值是一个 Promise 对象，并且，这个对象应该在数据加载完成时，来调用 resolve让 Promise对象的状态变为已完成
  loadMoreRows = ({ startIndex, stopIndex }) => {
    return new Promise(resolve => {
      API.get("/houses", {
        params: {
          cityId: this.state.localValue,
          ...this.filters,
          start: startIndex,
          end: stopIndex
        }
      })
      .then(res => {
        this.setState({
          list: [...this.state.list, ...res.data.body.list]
        })

        // 加载数据完成时，调用resolve即可
        resolve()
      })
    })
  }

  renderHouseList = () => {
    if(this.state.count === 0 && this.state.isShow) {
      return <NoHouse>当前筛选条件无数据,请更改筛选条件！</NoHouse>
    }

    return (
      <>
        <InfiniteLoader
          isRowLoaded={this.isRowLoaded}
          loadMoreRows={this.loadMoreRows}
          rowCount={this.state.count}
        >
          {({ onRowsRendered, registerChild }) => (
            <WindowScroller>
              {({ height, isScrolling, scrollTop }) => (
                <AutoSizer>
                  {({ width }) => (
                    <List
                      autoHeight
                      width={width}
                      height={height}
                      rowCount={this.state.count}
                      rowHeight={120}
                      rowRenderer={this.rowRenderer}
                      isScrolling={isScrolling}
                      scrollTop={scrollTop}
                      onRowsRendered={onRowsRendered}
                      ref={registerChild}
                    />
                  )}
                </AutoSizer>
              )}
            </WindowScroller>
          )}
        </InfiniteLoader>
      </>
    )
  }

  render() {
    return <div>
      <Flex className={styles.header}>
        <i className='iconfont icon-back' onClick={() => this.props.history.go(-1)}></i>
        <SearchHeader cityName={this.state.localCity} className={styles.searchHeader}> </SearchHeader>
      </Flex>

      <Sticky height={40}>
        <Filter onFilters={this.onFilters} />
      </Sticky>

      {this.renderHouseList()}
    </div>
  }
}
